import {
	CART_LIST,
	CART_ALL,
	UN_CART_ALL,
	CHECK_ITEM
} from './mutations-types';
import { Toast } from 'mint-ui';
import { MessageBox } from 'mint-ui';
import http from '@/common/api/request.js'
export default{
	state:{
		list:[],//是购物车的数据
		selectList:[] ,//选中的数据
		checkedsItem:[] //
	},
	getters:{
		isCheckedAll( state ){
			return state.list.length == state.selectList.length;
		},
		total(state){
			let total = {
				num:0,
				price:0
			}
			state.list.forEach(v=>{
				if( v.checked ){
					total.num += v.goods_num;
					total.price += v.goods_price * v.goods_num;
				}
			})
			return total;
		}
	},
	mutations:{
		[CART_LIST]( state, cartArr){
            state.list = cartArr;
            
			//state.selectList = cartArr;
			state.selectList = state.list.map(v=>{
				return v.id;
			})
			console.log(state.selectList);
            
		},
		//全选
		[CART_ALL]( state ){
			//  checkedsItem = state ? state.list : [];
			//  if (checkedsItem.length > 0) {
			//     checkedsItem.map(item => {
			//         state.selectList.push(item.title)
			// 		return item.id;
			//     })
			// }
			
            state.selectList = state.list.map(v=>{
                v.checked = true;
                return v.id;
            })
		},
		//全不选
		[UN_CART_ALL]( state ){
            state.list.forEach(v=>{
                v.checked = false;
            })
            state.selectList = [];
		},
		//单选
		[CHECK_ITEM]( state,index ){
			console.log(state.list[index].id);
			let id = state.list[index].id;
			let i = state.selectList.indexOf(id);
			//能在selectList找到对应的id
			if( i > -1 ){
				return state.selectList.splice(i,1);
			}
			//如果之前没有选中，就给selectList添加一个id进去
			state.selectList.push(id);
		},
		//删除
		delGoods(state){
			state.list = state.list.filter(v=>{
				return state.selectList.indexOf(v.id)== -1
			})
		}
	},
	//提交
	actions:{
		checkAllFn({commit,getters}){
			getters.isCheckedAll ? commit('UN_CART_ALL') : commit('CART_ALL');
		},
		//删除操作
		delGoodsFn({commit,state},id){
			//如果没有选中则提示信息
			if(state.selectList.length == 0){
				Toast('请选择商品');
			}
			let arrCart = [];
			MessageBox({
			  message: '确定要删除这些商品吗?',
			  showCancelButton: true
			}).then(()=>{
				if( typeof id == 'number'){
					//单个删除
					arrCart = [id];
					let index = state.list.findIndex(v=>{
						return v.id == id
					})
					console.log(index);
					state.list.splice(index,1);
				}else{
					//多选删除
					arrCart = state.selectList;
					commit('delGoods');
				}
				
				http.$axios({
					 url:'/api/deleteCart',
					 method:'post',
					 data:{
						 arrId:arrCart
					 }
				}).then(res=>{
					//state.list.splice(id,1);
					if( res.success ){
						Toast(res.msg);
					}
				})
			})
		}
	}
}